package com.gr.gojcodesandbox.codesandbox.java;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.gr.gojcodesandbox.codesandbox.CodeSandbox;
import com.gr.gojcodesandbox.common.JudgeInfoMessageEnum;
import com.gr.gojcodesandbox.model.ExecuteCodeRequest;
import com.gr.gojcodesandbox.model.ExecuteCodeResponse;
import com.gr.gojcodesandbox.model.ExecuteMessage;
import com.gr.gojcodesandbox.model.JudgeInfo;
import com.gr.gojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
public abstract class JavaCodeSandBoxTemplate implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    private static final long TIME_OUT = 5000L;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {

        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        // 1. 把用户的代码保存为文件
        File userCodeFile = saveCodeToFile(code);

        // 2. 编译代码，得到 class 文件
        ExecuteMessage compileFileExecuteMessage = compileFile(userCodeFile);
        if (compileFileExecuteMessage.getExitValue() != 0) {
            boolean b = deleteFile(userCodeFile);
            if (!b) {
                log.error("deleteFile error, userCodeFilePath = {}", userCodeFile.getAbsoluteFile());
            }
            return getErrorResponse(new Throwable("编译错误"), JudgeInfoMessageEnum.COMPILE_ERROR.getValue(), compileFileExecuteMessage.getErrorMessage());
        }
        System.out.println(compileFileExecuteMessage);

        // 3. 执行代码，得到输出结果
        List<ExecuteMessage> executeMessageList = runFile(userCodeFile, inputList);

        // 4. 收集整理输出结果
        ExecuteCodeResponse outputResponse = getOutputResponse(executeMessageList);

        // 5. 文件清理
        boolean b = deleteFile(userCodeFile);
        if (!b) {
            log.error("deleteFile error, userCodeFilePath = {}", userCodeFile.getAbsoluteFile());
        }
        return outputResponse;
    }

    /**
     * 1. 把用户的代码保存为文件
     * @param code 用户代码
     * @return
     */
    public File saveCodeToFile(String code) {
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局代码目录是否存在, 没有则新建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        return userCodeFile;
    }

    /**
     * 2. 编译代码，得到 class 文件
     * @param userCodeFile
     * @return
     */
    public ExecuteMessage compileFile(File userCodeFile) {
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsoluteFile());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
//            if (executeMessage.getExitValue() != 0) {
//                throw new RuntimeException("编译错误");
//            }
            return executeMessage;
        } catch (Exception e) {
            // return getErrorResponse(e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 3. 执行文件，获得执行结果列表
     * @param userCodeFile
     * @param inputList
     * @return
     */
//    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
//        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
//
//        List<ExecuteMessage> executeMessageList = new ArrayList<>();
//        for (String inputArgs: inputList) {
//            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
//
//            try {
//                Process runProcess = Runtime.getRuntime().exec(runCmd);
//                // 创建一个守护线程，实现程序超时中断
//                new Thread(() -> {
//                    try {
//                        Thread.sleep(TIME_OUT);
//                        runProcess.destroy();
//                    } catch (InterruptedException e) {
//                        throw new RuntimeException(e);
//                    }
//                }).start();
//                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
//                System.out.println(executeMessage);
//                executeMessageList.add(executeMessage);
//            } catch (Exception e) {
//                throw new RuntimeException("执行错误", e);
//            }
//        }
//        return executeMessageList;
//    }

    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();

        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (int i = 0; i < inputList.size(); i++) {
            // 添加 JVM 参数 -Xmx256m 和 -Dfile.encoding=UTF-8
            ProcessBuilder pb = new ProcessBuilder(
                    "java",
                    "-Xmx256m",          // 最大堆内存
                    "-Dfile.encoding=UTF-8",  // 设置文件编码
                    "-cp", userCodeParentPath,    // 类路径 tmpCode
                    "Main"               // 执行的主类
            );
            pb.redirectErrorStream(true);
            Process process = null;
            try {
                process = pb.start();
                // 创建一个守护线程，实现程序超时中断
//                Process finalProcess = process;
//                new Thread(() -> {
//                    try {
//                        Thread.sleep(TIME_OUT);
//                        finalProcess.destroy();
//                    } catch (InterruptedException e) {
//                        throw new RuntimeException(e);
//                    }
//                }).start();
                // 写入标准输入
                try (BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(process.getOutputStream()))) {
                    String text = inputList.get(i);
                    if (text != null && !text.isEmpty()) {
                        text = text.replace("\\n", "\n"); // 处理被转义的情况
                        String[] lines = text.split("\\r?\\n");
                        for (String line : lines) {
                            System.out.println(line);
                            writer.write(line);
                            writer.newLine();
                        }
                        writer.flush();
                    }
                } catch (IOException e) {
                    e.printStackTrace(); // 这里你可以根据业务需求换成日志或异常处理
                }
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(process, "运行");
                System.out.println(executeMessage);
                executeMessageList.add(executeMessage);
                if (executeMessage.getTime() > TIME_OUT) break;
            } catch (IOException e) {
                throw new RuntimeException("执行错误", e);
            }
        }
        return executeMessageList;
    }

    /**
     * 4. 整理获取输出结果
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        // 取用时最大值，便于判断是否超时
        long maxTime = 0;
        JudgeInfo judgeInfo = new JudgeInfo();
        for (ExecuteMessage executeMessage: executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (executeMessage.getTime() > TIME_OUT) {
                // 程序运行时间超过最大限制时间（可能有死循环）
                executeCodeResponse.setStatus(4);
                executeCodeResponse.setMessage(JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED.getValue());
                judgeInfo.setMessage(JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED.getValue());
                break;
            }
            if (StrUtil.isNotBlank(executeMessage.getErrorMessage())) {
                executeCodeResponse.setMessage(errorMessage);
                // 执行中存在错误
                executeCodeResponse.setStatus(3);
                judgeInfo.setMessage(JudgeInfoMessageEnum.RUNTIME_ERROR.getValue());
                judgeInfo.setErrorMessage(errorMessage);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (executeMessage.getTime() != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        // 正常运行完成
        judgeInfo.setTime(maxTime);
        judgeInfo.setMemory(1L);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }

    /**
     * 5. 删除文件
     * @param userCodeFile
     * @return
     */
    public boolean deleteFile(File userCodeFile) {
        if (userCodeFile.getParentFile() != null) {
            String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除" + (del ? "成功" : "失败"));
            return del;
        }
        return true;
    }

    /**
     * 获取错误响应
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e, String message, String errorMessage) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setMessage(message);
        judgeInfo.setErrorMessage(errorMessage);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }
}
